import { Singleton } from "./Singleton";

export class PostMessageHandler extends Singleton {
    public messageHandlers: Map<string, Function>;
    
    constructor() {
        super();
        this.messageHandlers = new Map();
        window.addEventListener('message', this.handleMessage.bind(this));
    }
  
    handleMessage(event) {
      const { data, origin } = event;
      const handler = this.messageHandlers.get(data.type);
      if (handler && (origin === '*' || origin === window.location.origin)) {
        handler(data.payload);
      }
    }
  
    //注册关于webPostMessage的消息监听
    addMessageHandler(type, handler) {
      this.messageHandlers.set(type, handler);
    }
  
    removeMessageHandler(type) {
      this.messageHandlers.delete(type);
    }
  
    //发送消息，type为消息类型，payload为消息内容，targetWindow为消息接收窗口
    //targetWindow值默认为父窗口
    postMessage(type, payload,targetWindow=window.parent) {
      console.log("postMessage",type,payload)
      targetWindow.postMessage({ type, payload }, '*');
    }
  }
  